package sdufe.lele.exception;


import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import sdufe.lele.result.ApiError;
import javax.servlet.http.HttpServletResponse;


/**
 * Created by olivia on 3/22/2017.
 *
 */

@ControllerAdvice
public class GlobalExceptionHandler {


    /**
     *
     * @param apiException
     * @param response
     * @return
     */
    @ExceptionHandler({sdufe.lele.exception.ApiException.class})
    @ResponseBody
    public ApiError handlerApiException(ApiException apiException,
                                        HttpServletResponse response) {
        if (!apiException.getPrintStackTrace().equals("no"))
            apiException.printStackTrace();

       //不能用spring管理，不能够应用单例模式
        ApiError apiError = new ApiError();
        apiError.setStatus(apiException.getHttpStatus());
        apiError.setMessage(apiException.getMessage());
        response.setStatus(apiError.getStatus());
        return apiError;
    }

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public ApiError handlerException(Exception exception,
                                     HttpServletResponse response) {
        ApiError apiError = new ApiError();
        exception.printStackTrace();
        apiError.setMessage(exception.getMessage());
        response.setStatus(apiError.getStatus());
        return apiError;
    }

    @ExceptionHandler({DuplicateKeyException.class})
    @ResponseBody
    public ApiError handlerSQLException(DuplicateKeyException duplicateKeyException,
                                     HttpServletResponse response) {
        ApiError apiError = new ApiError();
        duplicateKeyException.printStackTrace();
        apiError.setMessage("The Phone or Email were already registed!");
        apiError.setStatus(401);
        response.setStatus(apiError.getStatus());
        return apiError;
    }

    @ExceptionHandler({NullPointerException.class})
    @ResponseBody
    public ApiError handlerSQLException(NullPointerException nullPointerException,
                                        HttpServletResponse response) {
        ApiError apiError = new ApiError();
        nullPointerException.printStackTrace();
        apiError.setMessage("Internal error");
        apiError.setStatus(500);
        response.setStatus(apiError.getStatus());
        return apiError;
    }



}
